<template>
  <div class="contentwarp">
    <div class="toolsbar">
      <el-row>
        <el-col :span="24">
          <el-input placeholder="请输入地址" v-model="address" style="width:300px;"></el-input>
          <el-select v-model="cityValue" placeholder="请选择">
            <el-option v-for="item in citys" :key="item.value" :value="item.value">
            </el-option>
          </el-select>
          <el-button icon="el-icon-search" @click="searchAddress"></el-button>
        </el-col>
      </el-row>
    </div>
    <div v-loading="loading" id="qqmap">

    </div>
  </div>
</template>

<script>
import { TMap } from "../../utils/tmap";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      deviceData: [],
      qqMap: {}, // 地图资源
      markersArray: [], // 地图标记
      currentId: 0, // 当前操作的数据索引
      address: "", // 搜索地址
      searchService: null, // pio检索
      customZoomControl: null, // 地图关闭div
      cityValue: "请选择",
      citys: [
        { value: "儋州市" },
        { value: "北京" },
        { value: "上海" },
        { value: "天津" }
      ],
      geocoder: null, // 地址解析,
      loading: false, //加载中
      markers: [],
      circles: [],
      labels: []
    };
  },
  computed: {
    ...mapGetters(["GetQQMapKey"])
  },
  methods: {
    loadData: function(page) {
      let that = this;
      this.$axios
        .get(this.APIURL + "/device", { params: { page: page } })
        .then(function(data) {
          if (data !== false) {
            that.deviceData = data.data;
            that.qqMap.map.panTo(
              new qq.maps.LatLng(
                that.deviceData[0].latitude,
                that.deviceData[0].longitude
              )
            );
            for (let i of that.deviceData) {
              that.showMarker(i.id, i.latitude, i.longitude, i.address);
            }
          }
        });
    },
    initMap: function() {
      let that = this;
      TMap("BH3BZ-OWLW6-6KNSQ-MHGH5-ABJHZ-4KFW6").then(qq => {
        let that = this;
        that.qqMap.qq = qq;
        that.qqMap.center = new qq.maps.LatLng(
          40.01945601727397,
          116.46899342536926
        );
        /* eslint-disable no-new */
        that.qqMap.map = new qq.maps.Map(document.getElementById("qqmap"), {
          // 地图的中心地理坐标。
          center: that.qqMap.center,
          draggable: true,
          zoom: 15,
          disableDefaultUI: true
        });
        that.geocoder = new qq.maps.Geocoder();
        var latlngBounds = new qq.maps.LatLngBounds();
        //调用Poi检索类
        that.searchService = new qq.maps.SearchService({
          complete: function(results) {
            var pois = results.detail.pois;
            for (var i = 0, l = pois.length; i < l; i++) {
              var poi = pois[i];
              latlngBounds.extend(poi.latLng);
              var marker = new qq.maps.Marker({
                map: that.qqMap.map,
                position: poi.latLng
              });
              marker.setTitle(i + 1);
              that.markers.push(marker);
            }
            that.qqMap.map.fitBounds(latlngBounds);
          }
        });
        this.loadData();
      });
    },
    //清除覆盖物
    clearOverlays: function(overlays) {
      var overlay;
      while ((overlay = overlays.pop())) {
        overlay.setMap(null);
      }
    },
    showMarker: function(id, lat, lng, address) {
      let that = this;
      var center = new qq.maps.LatLng(lat, lng);
      var marker = new qq.maps.Marker({
        position: center,
        draggable: true,
        map: that.qqMap.map,
        id: id
      });
      var circle = new qq.maps.Circle({
        map: that.qqMap.map,
        center: center,
        radius: 500,
        fillColor: new qq.maps.Color(0, 0, 0, 0.4),
        strokeWeight: 0,
        id: id
      });
      var label = new qq.maps.Label({
        position: center,
        map: that.qqMap.map,
        content: address,
        id: id
      });
      this.circles.push(circle);
      this.markers.push(marker);
      this.labels.push(label);
      var listener = qq.maps.event.addListener(marker, "dragend", function() {
        that.setDeviceMap(marker.getPosition(), marker.id);
        that.loading = true;
      });
    },

    setDeviceMap: function(latLng, id) {
      let that = this;
      // 设置服务请求成功的回调函数
      this.geocoder.setComplete(function(r) {
        let adr = r.detail.addressComponents;
        if (adr.province === "北京市" || adr.province === "上海市") {
          adr.province = "";
        }
        let address =
          adr.province +
          adr.city +
          adr.district +
          adr.street +
          adr.streetNumber +
          adr.town;
        that.$axios
          .get(that.APIURL + "/device/setMap", {
            params: {
              id: id,
              lat: latLng.lat,
              lng: latLng.lng,
              address: address
            }
          })
          .then(function(response) {
            if (response !== false) {
              for (let i of that.circles) {
                if (i.id === id) {
                  i.setCenter(new qq.maps.LatLng(latLng.lat, latLng.lng));
                }
              }
              for (let i of that.labels) {
                if (i.id === id) {
                  i.setPosition(new qq.maps.LatLng(latLng.lat, latLng.lng));
                }
              }
              that.loading = false;
              that.$message({ type: "success", message: "位置更新成功!" });
            }
          });
      });
      // 对指定地址进行解析
      this.geocoder.getAddress(latLng);
    },
    searchAddress: function() {
      this.clearOverlays(this.markers);
      this.clearOverlays(this.circles);
      this.clearOverlays(this.labels);
      for(let i of this.deviceData){
        this.showMarker(i.id,i.latitude,i.longitude,i.address)
      }
      if (!this.address) {
        this.$message({ type: "error", message: "请输入地址!" });
      }
      if (!this.cityValue || this.cityValue === "请选择") {
        this.$message({ type: "error", message: "请选择区域!" });
      }
      this.searchService.setLocation(this.cityValue);
      this.searchService.search(this.address);
    }
  },
  mounted: function() {
    this.initMap();
  }
};
</script>

<style scoped>
.tableToolsbar {
  margin-bottom: 10px;
  display: none;
}

.transition-box {
  margin-bottom: 10px;
  width: 200px;
  height: 100px;
  border-radius: 4px;
  background-color: #409eff;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}
</style>